﻿using System;
using System.Linq;
using System.Net.NetworkInformation;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Navigation;
using CompanyHub.ViewModels;
using Microsoft.Phone.Controls;
using Windows.Foundation;
using Windows.Management.Deployment;
using Windows.Phone.Management.Deployment;
using GestureEventArgs = System.Windows.Input.GestureEventArgs;

namespace CompanyHub
{
    public partial class MainPage : PhoneApplicationPage
    {
        public MainPage()
        {
            InitializeComponent();

            // 设置数据上下文
            DataContext = App.ViewModel;
        }

        public bool IsLoadingAnimationVisible
        {
            get { return LoadingBar.Visibility == Visibility.Visible; }
            set { LoadingBar.Visibility = value ? Visibility.Visible : Visibility.Collapsed; }
        }

        // 从 ViewModel 获取数据
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                ReloadData();
            }

            CompanyAppList.SelectedItem = null;
        }

        #region 事件
        private async void CompanyAppLongListSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0 && e.AddedItems[0] is MainViewModel.AppInfo)
            {
                //重置已安装程序列表选中状态为空
                CompanyAppList.SelectedItem = null;

                var app = (MainViewModel.AppInfo)e.AddedItems[0];

                //当前程序正在安装，什么都不做
                if (app.InstallState.Equals(MainViewModel.AppInfo.PackageInstallState.Installing))
                    return;

                //启动程序
                if (app.InstallState.Equals(MainViewModel.AppInfo.PackageInstallState.Installed))
                {
                    try
                    {
                        InstallationManager.FindPackagesForCurrentPublisher()
                                           .Single(a => a.Id.Name.ToLower().Equals(app.Name.ToLower()))
                                           .Launch("");
                    }
                    catch (Exception ex)
                    {
                    }
                    return;
                }


                //安装程序
                if (!NetworkInterface.GetIsNetworkAvailable())
                {
                    MessageBox.Show("请连接网络");
                    return;
                }
                await InstallApp(app);
            }
        }

        //启动程序
        private void installedApp_Tap(object sender, GestureEventArgs e)
        {
            if (((FrameworkElement)sender).DataContext is MainViewModel.InstalledApp)
            {
                ((MainViewModel.InstalledApp)((FrameworkElement)sender).DataContext).Launch();
            }
        }

        #endregion

        #region 私有方法

        //重新载入数据
        private async void ReloadData()
        {
            IsLoadingAnimationVisible = true;
            await App.ViewModel.LoadData();
            InitInstalledAppPanel();

            IsLoadingAnimationVisible = false;
        }

        //更新已安装列表
        public void InitInstalledAppPanel()
        {
            InstalledAppLineOne.Children.Clear();
            InstalledAppLineTwo.Children.Clear();

            foreach (MainViewModel.InstalledApp item in App.ViewModel.installedApps)
            {
                var container = new Grid
                    {
                        Width = 200,
                        Height = 200,
                        DataContext = item,
                        Margin = new Thickness(0, 0, 10, 10),
                        Background = new SolidColorBrush(Color.FromArgb(255, 00, 125, 191))
                    };

                container.Tap += installedApp_Tap;

                //程序名
                var Tex = new TextBlock
                    {
                        Text = item.Name,
                        Margin = new Thickness(20, 0, 0, 15),
                        Foreground = new SolidColorBrush(Colors.White)
                    };
                Tex.SetValue(VerticalAlignmentProperty, VerticalAlignment.Bottom);

                //找到当前已安装程序的图标
                MainViewModel.AppInfo currentAppPackage =
                    App.ViewModel.CompanyApps.Single(a => a.Id.ToLower().Equals(item.Id.ToLower()));

                //程序图标
                var image = new Image
                    {
                        Stretch = Stretch.Fill,
                        Source = currentAppPackage.LoadedSource
                    };


                container.Children.Add(image);
                container.Children.Add(Tex);


                if (InstalledAppLineOne.Children.Count <= InstalledAppLineTwo.Children.Count)
                    InstalledAppLineOne.Children.Add(container);
                else
                    InstalledAppLineTwo.Children.Add(container);
            }
        }

        //安装程序
        public async Task InstallApp(MainViewModel.AppInfo app)
        {
            //获得当前安装进程的 IAsyncOperationWithProgress 对象
            IAsyncOperationWithProgress<PackageInstallResult, uint> result =
                InstallationManager.AddPackageAsync(app.Name, new Uri(app.Url));

            //
            result.Progress = (info, progressInfo) => Dispatcher.BeginInvoke(async () =>
                {
                    switch (info.Status)
                    {
                        case AsyncStatus.Canceled:
                            //安装进程被取消
                            app.InstallState = MainViewModel.AppInfo.PackageInstallState.NotInstalled;
                            return;
                        case AsyncStatus.Error:
                            //安装进程遇到错误
                            MessageBox.Show("安装失败！");
                            app.InstallState = MainViewModel.AppInfo.PackageInstallState.NotInstalled;
                            return;
                        case AsyncStatus.Completed:
                            break;
                        case AsyncStatus.Started:
                            //安装进程开始
                            app.InstallState = MainViewModel.AppInfo.PackageInstallState.Installing;
                            break;
                        default:
                            break;
                    }
                    //更新安装进程百分比
                    app.InstalltionProgressPercent = progressInfo;
                });

            result.Completed = (info, status) => Dispatcher.BeginInvoke(async () =>
                {
                    if (!status.Equals(AsyncStatus.Completed)) return;

                    
                    if (info.GetResults().InstallState.Equals(PackageInstallState.Installed))
                    {
                        //安装完成
                        app.InstallState = MainViewModel.AppInfo.PackageInstallState.Installed;
                        //更新界面
                        await App.ViewModel.LoadInstalledApps();
                        InitInstalledAppPanel();
                    }
                });
        }
        #endregion
    }
}